/*
 * Copyright (C), 2002-2017, 苏宁易购电子商务有限公司
 * FileName: ActivityRealtimeDataController.java
 * Author:   15060460
 * Date:     2017年3月27日 下午3:55:12
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.sawp.in.controller.member;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jxls.common.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.suning.framework.lang2.exception.BizzException;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.member.constant.MemberConstants;
import com.suning.sawp.member.service.ActivityRealtimeDataService;
import com.suning.sawp.member.service.ExportCustomerService;
import com.suning.sawp.member.vo.ActivityRealtimeDataVo;
import com.suning.sawp.member.vo.GridViewVo;
import com.suning.sawp.member.vo.QueryRealTimeDataVo;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.ExcelUtils;

/**
 * 外拓实时数据统计接口
 *
 * @author 15060460
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/adminPage/realtimeData")
public class ActivityRealtimeDataController {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

	@Resource
	private ActivityRealtimeDataService activityRealtimeDataService;

	@Resource
	private ExportCustomerService exportCustomerService;

	/**
	 * 给前端查询当前登陆用户角色使用
	 * 
	 * 0 总部 1分公司 2大区 4 门店
	 *
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "queryUserRole")
	@ResponseBody
	public ReturnMsg<String> queryUserRole() {
		EmployeeInfo info = RequestUserHolder.getRequestUser();
		ReturnMsg<String> returnMsg = new ReturnMsg<String>();
		try {// 0 总部 1分公司 2大区 4 门店
			if (StringUtils.equals(info.getOrgLevel(), MemberConstants.EmployeeOrgLevel.HQ)) {
				returnMsg.setData("0");
			} else if (StringUtils.equals(info.getOrgLevel(), MemberConstants.EmployeeOrgLevel.CAMPANY)) {
				returnMsg.setData("1");
			} else if (StringUtils.equals(info.getOrgLevel(), MemberConstants.EmployeeOrgLevel.AREA)) {
				returnMsg.setData("2");
			} else if (StringUtils.equals(info.getOrgLevel(), MemberConstants.EmployeeOrgLevel.SHOP) && StringUtils.equals(info.getPositionId(), ClerkConstants.STORE_KEEPER)) {
				// 店长
				returnMsg.setData("3");
			} else if (StringUtils.equals(info.getOrgLevel(), MemberConstants.EmployeeOrgLevel.SHOP) && StringUtils.equals(info.getPositionId(), ClerkConstants.SALE_GUIDE)) {
				// 督导
				returnMsg.setData("4");
			} else {
				returnMsg.setRetFlag(ReturnMsg.FAIL);
				returnMsg.setErrorMessage("当前用户：" + info);
			}
		} catch (Exception e) {
			LOGGER.error("queryUserRole异常", e);
			returnMsg.setRetFlag(ReturnMsg.FAIL);
			returnMsg.setErrorMessage(e.getMessage());
		}
		return returnMsg;
	}

	/**
	 * 总部权限查看某大区实时销售数据
	 *
	 * @param queryVo
	 *            必填：activityId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "queryRealtimeDataHq")
	@ResponseBody
	public ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> queryRealtimeDataHq(QueryRealTimeDataVo queryVo) {
		debugLog("入参：{}", queryVo);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = new ReturnMsg<GridViewVo<ActivityRealtimeDataVo>>();
		try {
			checkQueryVo(queryVo);
			List<ActivityRealtimeDataVo> data = new ArrayList<ActivityRealtimeDataVo>();
			GridViewVo<ActivityRealtimeDataVo> gridView = new GridViewVo<ActivityRealtimeDataVo>();
			ActivityRealtimeDataVo vo = activityRealtimeDataService.queryRealtimeDataHq(queryVo);
			if (vo != null) {
				data.add(vo);
				gridView.setCount(1l);
				gridView.setData(Lists.newArrayList(vo));
			}
			returnMsg.setData(gridView);
		} catch (Exception e) {
			LOGGER.info("入参：{}", queryVo);
			LOGGER.error("queryRealtimeDataHq异常", e);
			returnMsg.setRetFlag(ReturnMsg.FAIL);
			returnMsg.setErrorMessage(e.getMessage());
		}
		return returnMsg;
	}

	private void checkQueryVo(QueryRealTimeDataVo queryVo) {
		if (queryVo == null) {
			throw new BizzException("入参为空");
		}
		if (StringUtils.isEmpty(queryVo.getActivityId())) {
			throw new BizzException("activityId不能为空");
		}
	}

	@RequestMapping("downloadRealtimeDataHq")
	public void dowloadRealtimeDataHq(HttpServletRequest request, HttpServletResponse response, QueryRealTimeDataVo queryVo) {
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = this.queryRealtimeDataHq(queryVo);
		if (returnMsg.getData() != null && returnMsg.getData().getData() != null) {
			Context context = new Context();
			context.putVar("datas", returnMsg.getData().getData());
			context.putVar("name", "大区");
			String fileName = "大区拓展数据" + DateUtils.getNowShortStr() + ".xls";
			try {
				String filePath = getFilePath(request, "realTimeData.xls");
				ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
			} catch (Exception e) {
				LOGGER.error("dowloadRealtimeDataHq异常", e);
			}
		}
	}

	/**
	 * 大区、分公司 查询某活动下门店数据
	 *
	 * @param queryVo
	 *            必填：activityId,选填：memSource，memMode
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "queryRealtimeDataStore")
	@ResponseBody
	public ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> queryRealtimeDataStore(QueryRealTimeDataVo queryVo) {
		debugLog("入参：{}", queryVo);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = new ReturnMsg<GridViewVo<ActivityRealtimeDataVo>>();
		try {
			checkQueryVo(queryVo);
			GridViewVo<ActivityRealtimeDataVo> grid = activityRealtimeDataService.queryRealtimeDataStore(queryVo);
			returnMsg.setData(grid);
		} catch (Exception e) {
			LOGGER.info("入参：{}", queryVo);
			LOGGER.error("queryRealtimeDataStore异常", e);
			returnMsg.setRetFlag(ReturnMsg.FAIL);
			returnMsg.setErrorMessage(e.getMessage());
		}
		return returnMsg;
	}

	@RequestMapping("downloadRealtimeDataStore")
	public void dowloadRealtimeDataStore(HttpServletRequest request, HttpServletResponse response, QueryRealTimeDataVo queryVo) {
		// 导出，查全部
		queryVo.setPageNo(-1L);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = this.queryRealtimeDataStore(queryVo);
		if (returnMsg.getData() != null && returnMsg.getData().getData() != null) {
			Context context = new Context();
			context.putVar("datas", returnMsg.getData().getData());
			context.putVar("name", "门店");
			String fileName = "门店拓展数据" + DateUtils.getNowShortStr() + ".xls";
			try {
				String filePath = getFilePath(request, "realTimeData.xls");
				ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
			} catch (Exception e) {
				LOGGER.error("dowloadRealtimeDataStore异常", e);
			}
		}
	}

	/**
	 * 店长查询某活动下品类统计
	 *
	 * @param queryVo
	 *            必填：activityId,storeCode;选填：memSource，memMode,employeeId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "queryRealtimeDataCate")
	@ResponseBody
	public ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> queryRealtimeDataCate(QueryRealTimeDataVo queryVo) {
		debugLog("入参：{}", queryVo);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = new ReturnMsg<GridViewVo<ActivityRealtimeDataVo>>();
		try {
			checkQueryVo(queryVo);
			populateStoreCode(queryVo);
			debugLog("补充后入参：{}", queryVo);
			List<ActivityRealtimeDataVo> datas = activityRealtimeDataService.queryRealtimeDataCate(queryVo);
			GridViewVo<ActivityRealtimeDataVo> gridView = new GridViewVo<ActivityRealtimeDataVo>();
			gridView.setData(datas);
			gridView.setCount(Long.valueOf(datas.size()));
			if (!datas.isEmpty()) {
				gridView.setPageSize(gridView.getCount());
			}
			returnMsg.setData(gridView);
		} catch (Exception e) {
			LOGGER.info("入参：{}", queryVo);
			LOGGER.error("queryRealtimeDataCate异常", e);
			returnMsg.setRetFlag(ReturnMsg.FAIL);
			returnMsg.setErrorMessage(e.getMessage());
		}
		return returnMsg;
	}

	private void populateStoreCode(QueryRealTimeDataVo queryVo) {
		EmployeeInfo employee = RequestUserHolder.getRequestUser();
		if (employee == null) {
			throw new BizzException("未登录");
		}
		String rule = queryUserRole().getData();
		if (StringUtils.equals(rule, "0") || StringUtils.equals(rule, "1") || StringUtils.equals(rule, "2")) {// 总部，分公司，大区
			if (StringUtils.isEmpty(queryVo.getStoreCode())) {
				throw new BizzException("storeCode不能为空");
			}
		} else {
			queryVo.setStoreCode(employee.getStoreCode());// 门店
		}

	}

	@RequestMapping("downloadRealtimeDataCate")
	public void dowloadRealtimeDataCate(HttpServletRequest request, HttpServletResponse response, QueryRealTimeDataVo queryVo) {
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = this.queryRealtimeDataCate(queryVo);
		if (returnMsg.getData() != null && returnMsg.getData().getData() != null) {
			Context context = new Context();
			context.putVar("datas", returnMsg.getData().getData());
			context.putVar("name", "品类");
			try {
				/*
				 * EmployeeInfo info = RequestUserHolder.getRequestUser();
				 * String rule = queryUserRole().getData(); String filePath =
				 * getFilePath(request,"realTimeDataHasCust.xls"); if
				 * (StringUtils.equals(rule, "3")){//店长
				 * context.putVar("customers",
				 * this.exportCustomerService.queryCustormerForDz
				 * (queryVo.getActivityId(),
				 * info.getStoreCode(),null,queryVo.getMemSource
				 * (),queryVo.getExpandId())); }else{ filePath =
				 * getFilePath(request,"realTimeData.xls"); }
				 */
				String filePath = getFilePath(request, "realTimeData.xls");
				String fileName = "品类拓展数据" + DateUtils.getNowShortStr() + ".xls";
				ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
			} catch (Exception e) {
				LOGGER.error("dowloadRealtimeDataCate异常", e);
			}
		}
	}

	/**
	 * 店长或督导查询某活动下人员统计数据
	 *
	 * @param queryVo
	 *            必填：activityId,storeCode;选填：memMode,employeeId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "queryRealtimeDataEmployee")
	@ResponseBody
	public ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> queryRealtimeDataEmployee(QueryRealTimeDataVo queryVo) {
		debugLog("入参：{}", queryVo);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = new ReturnMsg<GridViewVo<ActivityRealtimeDataVo>>();
		try {
			checkQueryVoEmployeeOrPlace(queryVo);
			populateStoreCode(queryVo);
			populateEmployeeId(queryVo);
			debugLog("补充后入参：{}", queryVo);
			returnMsg.setData(activityRealtimeDataService.queryRealtimeDataEmployee(queryVo));
		} catch (Exception e) {
			LOGGER.info("入参：{}", queryVo);
			LOGGER.error("queryRealtimeDataEmployee异常", e);
			returnMsg.setRetFlag(ReturnMsg.FAIL);
			returnMsg.setErrorMessage(e.getMessage());
		}
		return returnMsg;
	}

	private void checkQueryVoEmployeeOrPlace(QueryRealTimeDataVo queryVo) {
		if (queryVo == null) {
			throw new BizzException("入参为空");
		}
		if (StringUtils.isEmpty(queryVo.getActivityId())) {
			throw new BizzException("activityId不能为空");
		}
		String rule = queryUserRole().getData();
		if (!StringUtils.equals(rule, "4") && StringUtils.isEmpty(queryVo.getCateCode())) {// 非督导
			throw new BizzException("cateCode不能为空");
		}

	}

	private void populateEmployeeId(QueryRealTimeDataVo queryVo) {
		String rule = queryUserRole().getData();
		if ((StringUtils.equals(rule, "4"))) {// 督导
			EmployeeInfo employee = RequestUserHolder.getRequestUser();
			queryVo.setEmployeeId(employee.getStaffId());// 工号
		}
	}

	@RequestMapping("downloadRealtimeDataEmployee")
	public void dowloadRealtimeDataEmployee(HttpServletRequest request, HttpServletResponse response, QueryRealTimeDataVo queryVo) {
		queryVo.setPageNo(-1L);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = this.queryRealtimeDataEmployee(queryVo);

		Context context = new Context();
		if (returnMsg.getData() != null && returnMsg.getData().getData() != null) {
			context.putVar("datas", returnMsg.getData().getData());
		} else {
			context.putVar("datas", new ArrayList<ActivityRealtimeDataVo>());
		}
		context.putVar("name", "员工");
		try {
			/*
			 * EmployeeInfo info = RequestUserHolder.getRequestUser(); String
			 * rule = queryUserRole().getData(); String filePath =
			 * getFilePath(request,"realTimeDataHasCust.xls"); if
			 * (StringUtils.equals(rule, "4")) {//督导 context.putVar("customers",
			 * this
			 * .exportCustomerService.queryCustormerForDd(queryVo.getActivityId
			 * (), info.getStoreCode(),
			 * info.getStaffId(),queryVo.getMemSource(),queryVo.getExpandId()));
			 * }else if(StringUtils.equals(rule, "3")){//店长
			 * context.putVar("customers",
			 * this.exportCustomerService.queryCustormerForDz
			 * (queryVo.getActivityId(), info.getStoreCode(),
			 * queryVo.getCateCode
			 * (),queryVo.getMemSource(),queryVo.getExpandId())); }else{
			 * filePath = getFilePath(request,"realTimeData.xls"); }
			 */
			String filePath = getFilePath(request, "realTimeData.xls");
			String fileName = "员工拓展数据" + DateUtils.getNowShortStr() + ".xls";
			ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
		} catch (Exception e) {
			LOGGER.error("dowloadRealtimeDataEmployee异常", e);
		}

	}

	/**
	 * 店长或督导查询某活动下外拓地点统计
	 *
	 * @param queryVo
	 *            必填：activityId,storeCode;选填：memMode,employeeId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "queryRealtimeDataPlace")
	@ResponseBody
	public ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> queryRealtimeDataPlace(QueryRealTimeDataVo queryVo) {
		debugLog("入参：{}", queryVo);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = new ReturnMsg<GridViewVo<ActivityRealtimeDataVo>>();
		try {
			checkQueryVoEmployeeOrPlace(queryVo);
			populateStoreCode(queryVo);
			populateEmployeeId(queryVo);
			debugLog("补充后入参：{}", queryVo);
			returnMsg.setData(activityRealtimeDataService.queryRealtimeDataPlace(queryVo));
		} catch (Exception e) {
			LOGGER.info("入参：{}", queryVo);
			LOGGER.error("queryRealtimeDataPlace异常", e);
			returnMsg.setRetFlag(ReturnMsg.FAIL);
			returnMsg.setErrorMessage(e.getMessage());
		}
		return returnMsg;
	}

	@RequestMapping("downloadRealtimeDataPlace")
	public void dowloadRealtimeDataPlace(HttpServletRequest request, HttpServletResponse response, QueryRealTimeDataVo queryVo) {
		queryVo.setPageNo(-1L);
		ReturnMsg<GridViewVo<ActivityRealtimeDataVo>> returnMsg = this.queryRealtimeDataPlace(queryVo);
		if (returnMsg.getData() != null && returnMsg.getData().getData() != null) {
			Context context = new Context();
			context.putVar("datas", returnMsg.getData().getData());
			context.putVar("name", "地点");
			try {
				/*
				 * EmployeeInfo info = RequestUserHolder.getRequestUser();
				 * String rule = queryUserRole().getData(); String filePath =
				 * getFilePath(request,"realTimeDataHasCust.xls"); if
				 * (StringUtils.equals(rule, "4")) {//督导
				 * context.putVar("customers",
				 * this.exportCustomerService.queryCustormerForDd
				 * (queryVo.getActivityId(), info.getStoreCode(),
				 * info.getStaffId
				 * (),queryVo.getMemSource(),queryVo.getExpandId())); }else
				 * if(StringUtils.equals(rule, "3")){//店长
				 * context.putVar("customers",
				 * this.exportCustomerService.queryCustormerForDz
				 * (queryVo.getActivityId(), info.getStoreCode(),
				 * queryVo.getCateCode
				 * (),queryVo.getMemSource(),queryVo.getExpandId())); }else{
				 * filePath = getFilePath(request,"realTimeData.xls"); }
				 */
				String filePath = getFilePath(request, "realTimeData.xls");
				String fileName = "地点拓展数据" + DateUtils.getNowShortStr() + ".xls";
				ExcelUtils.downloadTemplateExcel(filePath, fileName, context, response);
			} catch (Exception e) {
				LOGGER.error("dowloadRealtimeDataPlace异常", e);
			}
		}
	}

	/**
	 * 获取excel模板文件路径
	 *
	 * @param request
	 * @param fileName
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	private String getFilePath(HttpServletRequest request, String fileName) {
		String rootPath = request.getSession().getServletContext().getRealPath("");
		return rootPath + "/WEB-INF/classes/conf/excel/" + fileName;
	}

	private void debugLog(String msg, Object... object) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug(msg, object);
		}
	}

}
